package com.ruoyi.common.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ObjectUtils {
    /**
     * 合并多个对象为JSON字符串
     *
     * @param resources
     * @return
     */
    public static String mergeObj2JSONStr(Object... resources) {
        if (resources == null || resources.length == 0) {
            return "{}";
        }

        ObjectMapper mapper = new ObjectMapper();
        // 自定义 byte[] 反序列化器，去除空格和空值
        SimpleModule module = new SimpleModule();
        module.addDeserializer(byte[].class, new JsonDeserializer<byte[]>() {
            @Override
            public byte[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                byte[] value = p.getBinaryValue();
                return trimTrailingBytes(value);
            }
        });

        // 添加自定义序列化器
        module.addSerializer(byte[].class, new JsonSerializer<byte[]>() {
            @Override
            public void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                if (value != null) {
                    // 使用新的byte数组转换方法
                    gen.writeString(byteArrayToString(value));
                } else {
                    gen.writeNull();
                }
            }
        });
        mapper.registerModule(module);

        Map<String, Object> merged = new HashMap<>();

        // 遍历所有入参对象并合并
        for (Object resource : resources) {
            if (resource != null) {
                Map<String, Object> map = mapper.convertValue(resource, Map.class);
                merged.putAll(map);
            }
        }

        merged.forEach((key, value) -> {
            if (value instanceof String) {
                merged.put(key, ((String) value).trim());
            }
        });

        // 将合并后的Map转换为JSON字符串
        String json = null;
        try {
            json = mapper.writeValueAsString(merged);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * @param resources
     * @return
     */
    public static Map<String, Object>  mergeObj2Map(Object... resources) {
        if (resources == null || resources.length == 0) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        // 自定义 byte[] 反序列化器，去除空格和空值
        SimpleModule module = new SimpleModule();
        module.addDeserializer(byte[].class, new JsonDeserializer<byte[]>() {
            @Override
            public byte[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                byte[] value = p.getBinaryValue();
                return trimTrailingBytes(value);
            }
        });

        // 添加自定义序列化器
        module.addSerializer(byte[].class, new JsonSerializer<byte[]>() {
            @Override
            public void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                if (value != null) {
                    // 使用新的byte数组转换方法
                    gen.writeString(byteArrayToString(value));
                } else {
                    gen.writeNull();
                }
            }
        });
        mapper.registerModule(module);

        Map<String, Object> merged = new HashMap<>();

        // 遍历所有入参对象并合并
        for (Object resource : resources) {
            if (resource != null) {
                Map<String, Object> map = mapper.convertValue(resource, Map.class);
                merged.putAll(map);
            }
        }

        merged.forEach((key, value) -> {
            if (value instanceof String) {
                merged.put(key, ((String) value).trim());
            }
        });
        return merged;
    }


    public static String obj2JSONStr(Object resource) {
        ObjectMapper mapper = new ObjectMapper();
        // 自定义 byte[] 反序列化器，去除空格和空值
        SimpleModule module = new SimpleModule();
        module.addDeserializer(byte[].class, new JsonDeserializer<byte[]>() {
            @Override
            public byte[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                byte[] value = p.getBinaryValue();
                return trimTrailingBytes(value);
            }
        });

        // 添加自定义序列化器
        module.addSerializer(byte[].class, new JsonSerializer<byte[]>() {
            @Override
            public void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                if (value != null) {
                    // 使用新的byte数组转换方法
                    gen.writeString(byteArrayToString(value));
                } else {
                    gen.writeNull();
                }
            }
        });

        mapper.registerModule(module);

        Map<String, Object> map = new HashMap<>();
        try {
            map = mapper.convertValue(resource, Map.class);
            Map<String, Object> finalMap = map;
            map.forEach((key, value) -> {
                if (value instanceof String) {
                    finalMap.put(key, ((String) value).trim());
                } else {
                    finalMap.put(key, value);
                }
            });
            return mapper.writeValueAsString(finalMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 新增方法：将byte数组直接转换为字符串
    public static String byteArrayToString(byte[] bytes) {
        if (bytes == null) return null;
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            // 去掉空字符（byte值为0），其他字节转换为对应字符
            if (b != 0) {
                sb.append((char) b);
            }
        }
        return sb.toString();
    }

    // 提取byte[]处理方法，供序列化器和反序列化器使用
    static byte[] trimTrailingBytes(byte[] bytes) {
        if (bytes == null) return null;
        int end = bytes.length;
        // 增加对空格字符(32)的处理
        while (end > 0 && (bytes[end - 1] == 0x20 || bytes[end - 1] == 0x00 || bytes[end - 1] == 32)) {
            end--;
        }
        // 如果所有字符都是空格或空值，则返回null
        if (end == 0) {
            return null;
        }
        // 去除开头的空格和空值
        int start = 0;
        while (start < end && (bytes[start] == 0x20 || bytes[start] == 0x00 || bytes[start] == 32)) {
            start++;
        }
        return Arrays.copyOfRange(bytes, start, end);
    }
}
